package com.docios.cookbook2.ui.otherPager;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.docios.cookbook2.Dao.AppDatabase;
import com.docios.cookbook2.Dao.DatabaseImpl;
import com.docios.cookbook2.Dao.QueryBeanDao;
import com.docios.cookbook2.databinding.FragmentFavoriteBinding;
import com.docios.cookbook2.entity.QueryBean;
import com.docios.cookbook2.ui.adapter.ItemCommonFoodAdapter;

import java.util.ArrayList;
import java.util.List;

public class FavoriteFragment extends Fragment {
    QueryBeanDao queryBeanDao;
    AppDatabase db;
    List<QueryBean> fQueryBeans = new ArrayList<>();
    FragmentFavoriteBinding favoriteBinding;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        favoriteBinding = FragmentFavoriteBinding.inflate(getLayoutInflater());

        initData();
        favoriteBinding.topAppBar.setNavigationOnClickListener(v -> getActivity().finish());
        searchOnClick();

        return favoriteBinding.getRoot();
    }

    private void initData() {
        db = DatabaseImpl.setInstance(getActivity());
        //数据库查询
        queryBeanDao = db.queryBeanDao();
        fQueryBeans = queryBeanDao.getAllQ();
        //加入子view
        ItemCommonFoodAdapter adapter = new ItemCommonFoodAdapter(getActivity(), fQueryBeans);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        favoriteBinding.favoriteRecycle.setLayoutManager(layoutManager);
        favoriteBinding.favoriteRecycle.setAdapter(adapter);
    }

    private void searchOnClick() {

        //可用
        favoriteBinding.favorSearchBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 当用户提交搜索文本时执行的操作
                Toast.makeText(getContext(), query, Toast.LENGTH_SHORT).show();
                return true;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                // 当搜索文本发生变化时执行的操作

                return false;
            }
        });
    }


    /*
     * 当Fragment可见并主动运行时调用
     * */
    @Override
    public void onResume() {
        super.onResume();
        fQueryBeans.clear();
        initData();
    }

}